package servlets;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import database.DBHandler;
import database.DatabaseInterface;
import forum.Post;

/**
 * Servlet implementation class ViewPostsProcessor
 */
// @WebServlet("/ViewPostsProcessor")
public class ViewPostsProcessor extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewPostsProcessor() {
		super();
	}

	/**
	 * @see Servlet#init()
	 */
	public void init() throws ServletException {
		super.init();
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		super.destroy();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("view posts processor. doGet");
		// get session of the request
		HttpSession session = request.getSession();

		Boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");

		if (isLoggedIn == null || !(isLoggedIn.booleanValue())) {
			request.setAttribute("errorMsg", "Please Log In");
			String addr = "http://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath();

			request.setAttribute("errorLink", addr);
			// get the request dispatcher
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/Error.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
			return;
		}

		// init the simulate DB
		DatabaseInterface db = DBHandler.getInstance();

		// session.setAttribute("username", "username0");

		// get parameter do of the request
		String action = request.getParameter("do");
		Integer forumID = (Integer) session.getAttribute("forumID");
		Integer threadID = (Integer) session.getAttribute("threadID");
		String username = (String) session.getAttribute("username");

		// get the id of the request
		int id = -1;
		if (request.getParameter("id") != null)
			id = Integer.valueOf(request.getParameter("id"));

		Post p = db.getPost(id);
		request.setAttribute("post", p);

		if (action.equals("edit")) {

			// only author of the post can edit the post
			if (!p.getAuthor().equalsIgnoreCase(username)) {
				request.setAttribute("errorMsg",
						"You do not have a suitable permittions to edit this post");
				String addr = "http://" + request.getServerName() + ":"
						+ request.getServerPort() + request.getContextPath()
						+ "/viewPosts";

				request.setAttribute("errorLink", addr);
				// get the request dispatcher
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher("/jsp/Error.jsp");

				// forward to the jsp file to display the book list
				dispatcher.forward(request, response);
				return;
			}

			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/editPost.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
			return;
		}

		// add reply
		if (action.equals("reply")) {
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/addReply.jsp");
			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
			return;

		}
		if (action.equals("delete")) {

			Boolean isModerator = (Boolean) session.getAttribute("isModerator");

			if (forumID == null || p.getAuthor() == null)
				return;

			// if username is author of thread or is moderator
			if (!p.getAuthor().equalsIgnoreCase(username)
					&& (isModerator == null || !isModerator.booleanValue())) {
				request.setAttribute("errorMsg",
						"You do not have a suitable permittions to delete this post");
				String addr = "http://" + request.getServerName() + ":"
						+ request.getServerPort() + request.getContextPath()
						+ "/viewPosts";

				request.setAttribute("errorLink", addr);
				// get the request dispatcher
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher("/jsp/Error.jsp");

				// forward to the jsp file to display the book list
				dispatcher.forward(request, response);
				return;
			}

			// delete the forum by id
			db.removeReply(id);

			// redirect to the book list servlet
			response.sendRedirect(request.getContextPath() + "/viewPosts");
			return;

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("view posts processor. doPost");

		// get session of the request
		HttpSession session = request.getSession();

		// init the simulate DB
		DatabaseInterface db = DBHandler.getInstance();

		// get book properties from the request
		int id = 0;

		try {
			id = Integer.parseInt(request.getParameter("id"));
		} catch (NumberFormatException e) {
		}

		String action = request.getParameter("action");
		Integer forumID = (Integer) session.getAttribute("forumID");
		Integer threadID = (Integer) session.getAttribute("threadID");
		String content = request.getParameter("content");

		if (action.equals("reply")) {
			String subject = request.getParameter("subject");
			String username = (String) session.getAttribute("username");
			Date tmp = GregorianCalendar.getInstance().getTime();
			SimpleDateFormat format = new SimpleDateFormat(
					"dd.MM.yyyy HH-mm-ss");
			String date = format.format(tmp);
			db.addReply(id, username, subject, content, date);
			response.sendRedirect(request.getContextPath() + "/viewPosts");
			return;

		}
		if (action.equals("edit")) {
			db.editPost(id, content);
			response.sendRedirect(request.getContextPath() + "/viewPosts");
			return;
		}
	}

}
